/**
 * $Id: DealReportHistoryThread.java,v 1.18 2006/10/02 02:21:02 martin Exp $
 *
 * Copyright 2006 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.runner.process;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.MTStatusAndReportBean;
import com.haoxi.gateway.common.SQLConst;
import com.haoxi.gateway.common.SYSConst;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.util.db.DBConnectUtil;
import com.haoxi.gateway.util.db.DealOracleDBUtil;

/**
 * 主要用于处理已成功发送MT的Report历史记录处理
 * 
 * Revision History
 * 
 * 2006-5-31,star.Zhao,created it
 */
public class DealReportHistoryThread extends TimerTask {

    private final static Log log = LogFactory
            .getLog(DealReportHistoryThread.class);
    /**
     * 定时检测时间
     */
    // private int delay;
    private String name;

    boolean running = false;

    public DealReportHistoryThread() {
        // this.delay = delay;
        this.name = "DealReportHistoryThread";
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        log.debug("DealReportHistoryThread Thread start()!");
        Map systemConf = null;
        String gateway_history = null;
        String gateway_DBName = null;
        List dealData = null;
        int num = 0;
        try {
            systemConf = RunnerMgr.getInstance().getSystemConf();
            Object tmp = systemConf.get(SYSConst.CONF_DB_HISTORY);
            if (null == tmp) {
                gateway_history = "history";
            } else {
                gateway_history = (String) tmp;
            }
            tmp = systemConf.get(SYSConst.CONF_DB_MYSQL);
            if (null == tmp) {
                gateway_DBName = "gateway";
            } else {
                gateway_DBName = (String) tmp;
            }
            dealData = getNeedDealReportMsg(gateway_DBName);
            num = dealData.size();
            log.debug("saveMsgHistoryStatus size[" + num + "]");
            if (num > 0) {
                if (DealOracleDBUtil.saveMsgHistoryStatus(this.name, dealData,
                        gateway_history)) {
                    // 删除已经处理状态报告的MT记录和Report临时信息
                    deleteDealed(dealData, gateway_DBName);
                    log.debug("saveMsgHistoryStatus ok!");

                } else {
                    log.debug("save msghistory in excuteBatch fail!");
                }
            }
        } catch (Exception ex) {
            log.error("catch other Exception:", ex);
        }
    }

    /**
     * 匹配需要处理状态报告
     * 
     * @return
     */
    private List getNeedDealReportMsg(String dbName) {
        List result = new ArrayList();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int dealReportSpeed = 0;
        try {
            Map sysCofn = RunnerMgr.getInstance().getSystemConf();
            Object tmp = sysCofn.get(SYSConst.CONF_DEALREPORT_SPEED);
            if (null == tmp) {
                dealReportSpeed = 200;
            } else {
                dealReportSpeed = ((Integer) sysCofn
                        .get(SYSConst.CONF_DEALREPORT_SPEED)).intValue();
            }

            conn = DBConnectUtil.open(dbName);
            ps = conn.prepareStatement(SQLConst.SELECT_NEED_DEAL_REPORT
                    + dealReportSpeed);
            rs = ps.executeQuery();
            MTStatusAndReportBean mtStatusAndReport = null;
            while (rs.next()) {
                mtStatusAndReport = new MTStatusAndReportBean();
                mtStatusAndReport.setMsgId(rs.getString("id"));
                mtStatusAndReport.setSubmitStatus(rs.getString("SUBMITSTATUS"));
                mtStatusAndReport.setSequenceID(rs.getString("SEQUENCEID"));
                mtStatusAndReport.setStype(rs.getInt("STYPE"));
                mtStatusAndReport.setServiceId(rs.getString("SERVICE_ID"));
                mtStatusAndReport.setOrgMobile(rs.getString("ORGMOBILE"));
                mtStatusAndReport.setOrgMobileType(rs.getInt("ORGMOBILETYPE"));
                mtStatusAndReport.setDestMobile(rs.getString("DEDESTMOBILE"));
                mtStatusAndReport
                        .setDestMobileType(rs.getInt("DESTMOBILETYPE"));
                mtStatusAndReport.setFeeMobile(rs.getString("FEEMOBILE"));
                mtStatusAndReport.setFeeMobileType(rs.getInt("FEEMOBILETYPE"));
                mtStatusAndReport.setFeeType(rs.getString("FEETYPE"));
                mtStatusAndReport.setFeeCode(rs.getInt("FEECODE"));
                mtStatusAndReport.setMsgContent(rs.getString("CONTENT"));
                mtStatusAndReport.setProvice(rs.getInt("PROVINCE"));
                mtStatusAndReport.setCity(rs.getInt("CITYNUMBER"));
                mtStatusAndReport.setCityName(rs.getString("CITYNAME"));
                mtStatusAndReport.setLinkID(rs.getString("RESERVED"));
                mtStatusAndReport.setCp(rs.getInt("CP"));
                mtStatusAndReport.setGateWayCode(rs.getString("GATEWAYCODE"));
                mtStatusAndReport.setSubmitTime(rs.getString("SUBMITTIME"));
                mtStatusAndReport.setMsgReport(rs.getString("STATUS"));
                mtStatusAndReport.setDoneTime(rs.getString("doneTime"));
                mtStatusAndReport.setSid(rs.getString("SID"));
                mtStatusAndReport.setMomtRelateID(rs.getString("MOMT_ID"));
                result.add(mtStatusAndReport);
            }
        } catch (SQLException e) {
            log.error("SQLException:", e);
        } catch (Exception e) {
            log.error("other Exception:", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.clearBatch();
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                log.error("close:", e);
            }
        }
        return result;
    }

    /**
     * delete dealed mt
     * 
     * @param ids
     */
    private void deleteDealed(List dealData, String dbName) {
        if (dealData == null || dealData.size() <= 0) {
            return;
        }
        int num = dealData.size();
        Connection conn = null;
        PreparedStatement psForSendedMT = null;
        PreparedStatement psForReport = null;
        try {
            conn = DBConnectUtil.open(dbName);
            psForSendedMT = conn
                    .prepareStatement(SQLConst.DELETE_NEED_REPORT_MTDATA);
            psForReport = conn.prepareStatement(SQLConst.DELETE_MT_REPORT_DATA);
            Iterator itr = dealData.iterator();
            while (itr.hasNext()) {
                String msgId = ((MTStatusAndReportBean) itr.next()).getMsgId();
                psForSendedMT.setString(1, msgId);
                psForReport.setString(1, msgId);
                psForSendedMT.addBatch();
                psForReport.addBatch();

            }
            int[] res = psForSendedMT.executeBatch();

            if (res.length == num) {
                log
                        .debug("delete needReportMT Data OK! the number of dealing result are: "
                                + num);
            } else {
                log.error("delete needReportMT failure !!!!!!");
            }

            int[] res1 = psForReport.executeBatch();

            if (res1.length == num) {
                log
                        .debug("delete MTReport OK! the number of dealing result are: "
                                + num);
            } else {
                log.error("delete MTReport failure !!!!!!");
            }

        } catch (SQLException e) {
            log.error("SQLException:", e);
        } catch (Exception e) {
            log.error("other Exception:", e);
        } finally {
            try {
                if (psForSendedMT != null) {
                    psForSendedMT.clearBatch();
                    psForSendedMT.close();
                }

                if (psForReport != null) {
                    psForReport.clearBatch();
                    psForReport.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                log.error("close:", e);
            }
        }
    }
}
